package com.falcon.generator.java.mapper;

import com.falcon.config.GeneratorConfig;
import com.falcon.enums.GeneratorTypeEnum;
import com.falcon.mapper.IColumnMapper;
import com.falcon.mapper.ITableMapper;
import com.falcon.constants.FtlConstant;
import com.falcon.domain.po.ColumnPO;
import com.falcon.domain.po.TablePO;
import com.falcon.utils.PathUtil;
import com.falcon.generator.java.JavaAbsGenerator;
import com.swan.core.utils.DateUtil;
import com.swan.core.utils.TxtFileUtil;
import com.swan.mybatis.condition.Condition;
import com.swan.mybatis.condition.OpType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zongf
 * @since 2023-05-18
 **/
@Slf4j
@Service
public class MapperXmlCodeGenerator extends JavaAbsGenerator {

    @Autowired
    private ITableMapper genTableMapper;

    @Autowired
    private IColumnMapper columnMapper;


    @Override
    public void generateCode(Long tableId) {

        // 1.配置信息
        GeneratorConfig.ClassConfig classConfig = config.getMapper();


        TablePO tablePO = this.genTableMapper.selectById(tableId);

        Condition condition = Condition.newInstance().and(ColumnPO.Fields.tableId, OpType.equals, tablePO.getId());
        List<ColumnPO> ColumnPOs = this.columnMapper.selectList(condition);
        String module = tablePO.getModuleName().split("-")[1];

        // 根据模板生成代码
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("table", tablePO);
        dataMap.put("module", module);
        dataMap.put("columns", ColumnPOs);
        dataMap.put("config", config);
        dataMap.put("author", config.getAuthor());
        dataMap.put("createDate", DateUtil.getToday());

        // 生成代码
        String code = freemarkerTemplateInside.getContent(FtlConstant.FTL_MAPPER_XML, dataMap);

        // 文件路径
        String fileName = getName(classConfig.getNamePrefix(), tablePO.getClassName(), classConfig.getNameSuffix());
        String modulePath = this.geGenerateCodePath() + "/" + tablePO.getModuleName();
        String filePath = PathUtil.getXmlPath(modulePath, config.getMapper().getXmlDir(), fileName);

        // 写入文件
        TxtFileUtil.writeFile(filePath, true, code);
    }

    @Override
    public GeneratorTypeEnum codeType() {
        return GeneratorTypeEnum.Java_Mapper_Xml;
    }

}
